<template>
  <div id="ai-container">
    <div id="chat-box">
      <div id="chat-history" ref="chatHistory">
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in activities"
            :key="index"
            :timestamp="activity.timestamp"
            :color="activity.color"
          >
            <div class="message-row" :class="{ 'user-row': activity.isUser, 'ai-row': !activity.isUser }">
              <img class="avatar" :src="activity.isUser ? userAvatar : aiAvatar" />
              <div
                :class="{
                  'user-message': activity.isUser,
                  'ai-message': !activity.isUser
                }"
                v-html="activity.content"
              />
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
      <div id="chat-input">
        <el-input
          v-model="msg"
          type="text"
          placeholder="请输入你的问题"
          @keydown.enter="sendMsg"
        />
        <el-button @click="sendMsg">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { addHistory ,addHistoryRedis} from '@/api/aihistory/history' // 你封装的新增API

export default {
  name: 'AIChat',
  data() {
    return {
      msg: '',
      eventSource: null,
      userAvatar: 'https://i.pravatar.cc/50?u=user',
      aiAvatar: 'https://api.dicebear.com/7.x/bottts/svg?seed=ai',
      sendAudio: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-message-pop-alert-2354.mp3'),
      activities: [
        {
          content: '🤖 欢迎来到京龙的 AIHospitalHealer！请问有什么可以帮您的？',
          timestamp: new Date().toLocaleString(),
          color: '#0bbd87',
          isUser: false
        }
      ]
    };
  },
  methods: {
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatHistory;
        container.scrollTop = container.scrollHeight;
      });
    },
    sendMsg() {
      if (!this.msg.trim()) return;

      this.sendAudio.play();

      if (this.eventSource) this.eventSource.close();

      const userMsg = {
        content: `🧑‍💻 ${this.msg}`,
        timestamp: new Date().toLocaleString(),
        isUser: true
      };

      this.activities.push(userMsg);

      const placeholderIndex = this.activities.length;
      const aiMsg = {
        content: '...',
        timestamp: new Date().toLocaleString(),
        color: '#0bbd87',
        isUser: false
      };
      this.activities.push(aiMsg);

      const encoded = encodeURIComponent(this.msg);
      this.msg = '';

      this.eventSource = new EventSource(`http://localhost:8080/ai/generateStreamAsString?message=${encoded}`);

      this.eventSource.onopen = () => {
        this.activities[placeholderIndex].content = '';
      };

      this.eventSource.onmessage = (event) => {
        if (event.data === '[complete]') {
          this.eventSource.close();

          // 保存对话历史
          const chatHistory = {
            sessionName: '',
            messages: JSON.stringify([
              {
                content: userMsg.content,
                isUser: true,
                timestamp: userMsg.timestamp
              },
              {
                content: this.activities[placeholderIndex].content,
                isUser: false,
                timestamp: this.activities[placeholderIndex].timestamp
              }
            ])
          };

          addHistory(chatHistory).then(() => {
            console.log('对话保存成功');
          });
          // addHistoryRedis(chatHistory).then(() => {
          //   console.log('对话保存成功(redis)');
          // });

          return;
        }

        this.activities[placeholderIndex].content += event.data;
        this.scrollToBottom();
      };
    }
  }
};
</script>

<style scoped>
#ai-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30px;
  min-height: 100vh;
  background: linear-gradient(to right, #e3f2fd, #fce4ec);
}

#chat-box {
  width: 100%;
  max-width: 800px;
  height: 90vh;
  background-color: #fff;
  border-radius: 20px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

#chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #fafafa;
}

#chat-input {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #f0f0f0;
  border-top: 1px solid #e0e0e0;
}

#chat-input .el-input {
  flex: 1;
  margin-right: 15px;
}

#chat-input .el-button {
  width: 100px;
  background-color: #42b983;
  color: white;
  font-weight: bold;
  border-radius: 10px;
  transition: background-color 0.3s ease;
}

#chat-input .el-button:hover {
  background-color: #38a174;
}

.message-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}
.user-row {
  flex-direction: row-reverse;
}
.ai-row {
  flex-direction: row;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin: 0 10px;
}

.user-message,
.ai-message {
  padding: 12px 18px;
  border-radius: 15px;
  max-width: 75%;
  word-wrap: break-word;
  font-size: 15px;
  line-height: 1.5;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.user-message {
  background-color: #d1ecf1;
  color: #0c5460;
}

.ai-message {
  background-color: #fff3cd;
  color: #856404;
}

#chat-history::-webkit-scrollbar {
  width: 6px;
}
#chat-history::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 3px;
}
</style>

